#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>

void reader(int rfd)
{
    char buffer[1024];
    while(1)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        printf("message: %s\n", buffer);
        sleep(1);
    }
}
void writer(int wfd)
{
    char* str = "I am father";
    char buf[1024];
    int cnt = 1;
    pid_t pid = getpid();
    while(1)
    {
        snprintf(buf, sizeof(buf), "message: %s, pid: %d, cnt: %d", str, pid, cnt);
        write(wfd, buf, sizeof(buf));
        cnt++;
        sleep(1);
    }
}
int main()
{
    //1、创建管道
    int pipefd[2];
    int n = pipe(pipefd);
    if(n < 0) return 1;

    //2、创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //子进程读
        close(pipefd[1]);//关闭写
        reader(pipefd[0]);//读
        exit(0);
    }
    //父进程写
    close(pipefd[0]);//关闭读
    writer(pipefd[1]);//写
    wait(NULL);//防止僵尸
    return 0;
}